import { Injectable } from "@nestjs/common";
// import { CreateUserDto } from "./dto/create-user.dto";
// import { UpdateUserDto } from "./dto/update-user.dto";
import { LoginUserDto } from "./dto/login-user.dto";
import { ChangePasswordUserDto } from "./dto/changePassword-user.dto";
import { InjectRepository } from "@nestjs/typeorm";
import { User } from "./entities/user.entity";
import { Repository, Like } from "typeorm";
import { ResponseUtils } from "../common/utils/esponse.util";
import { CryptoUtils } from "../common/utils/crypto.util";
import { AuthService } from "../auth/auth.service";
import { ListUserDto } from "./dto/list-user.dto";

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private authService: AuthService
  ) {}
  async login(loginUserDto: LoginUserDto) {
    // console.log(loginUserDto);
    // const data = await this.userRepository.findOne({ where: { username: loginUserDto.username } });
    // console.log(data);
    const data = await this.userRepository
      .createQueryBuilder("user")
      .addSelect("user.password")
      .where("user.username = :username", { username: loginUserDto.username })
      .getOne();
    console.log(data);
    if (!data) return ResponseUtils.error("暂无用户");
    if (data.status === 0) return ResponseUtils.error("用户已被禁用");
    const decryptPassword = CryptoUtils.decrypt(loginUserDto.password);

    if (!CryptoUtils.compare(decryptPassword, data.password)) return ResponseUtils.error("密码错误");

    const token = await this.authService.anthJwt(data);

    return ResponseUtils.success(token);
  }

  // create(createUserDto: CreateUserDto) {
  //   return "This action adds a new user";
  // }

  async findOne(username: LoginUserDto["username"]) {
    const data = await this.userRepository.findOne({ where: { username: username } });
    if (!data) return ResponseUtils.error("用户已被删除");
    return ResponseUtils.success(data);
  }

  async changePassword(username: LoginUserDto["username"], body: ChangePasswordUserDto) {
    const { oldPassword, newPassword } = body;
    const data = await this.userRepository.findOne({ where: { username: username } });
    const decryptOldPassword = CryptoUtils.decrypt(oldPassword);
    const decryptNewPassword = CryptoUtils.decrypt(newPassword);
    if (!CryptoUtils.compare(decryptOldPassword, data.password)) return ResponseUtils.error("密码错误");
    if (oldPassword === newPassword) return ResponseUtils.error("新密码不能和旧密码相同");
    data.password = CryptoUtils.hashSync(decryptNewPassword);
    // 保存新密码到数据库
    await this.userRepository.save(data);
    return ResponseUtils.success("密码修改成功");
  }

  async findList(query: ListUserDto) {
    const { page, pageSize, keyword } = query;
    const [userList, total] = await this.userRepository.findAndCount({
      // 根据roleIds查询role表中的数据
      where: [{ name: Like(`%${keyword}%`) }, { username: Like(`%${keyword}%`) }],
      relations: ["roles"],
      take: pageSize,
      skip: (page - 1) * pageSize
    });
    return ResponseUtils.success({
      data: userList,
      total: total
    });
  }

  // update(id: number, updateUserDto: UpdateUserDto) {
  //   return `This action updates a #${id} user`;
  // }

  // remove(id: number) {
  //   return `This action removes a #${id} user`;
  // }
}
